<?php
namespace app\admin\controller;
use think\Controller;
use think\Request;
use think\Db;
use think\Log;
use lib\Data;
/**
 * 权限管理控制器
 * @authors ChuckWe (s312906342@gmail.com)
 * @date    2018-04-19 14:01:43
 * @version $Id$
 */

class Admin extends Common  {
    
    public function add(){
        
        if(Request::instance()->isAjax()){
            $data['username'] = trim(input('post.username'));
            $data['password1'] = trim(input('post.password1'));
            $data['password2'] = trim(input('post.password2'));
            $data['phone']  = trim(input('post.phone'));
            $data['email']  = trim(input('post.email'));
            $data['uid']    = intval(input('post.rule'));
            $data['register_time']  = time();
                if($data['username'] == null || $data['password1'] == null || $data['password2'] == null ){
                    $json['code']=403;
                    $json['msg']='带星号的为必填';
                    return json($json);
                }
                if(!preg_match('/^[A-Za-z0-9]{4,40}$/',$data['username'])){
                $json['code']=402;
                $json['msg']='用户名不能为汉字';
                return json($json);
                }
                if(!preg_match('/^[a-zA-Z]\w{5,17}$/',$data['password1'])){
                    $json['code']=401;
                    $json['msg']='密码字母开头，6-18之间';
                    return json($json);
                }
                if( $data['password1'] !== $data['password2']){
                    $json['code']=404;
                    $json['msg']='错误,密码必须相同';
                    return json($json);
                }
               
            $data['password'] = md5(md5($data['password1']).md5('ChuckWe'));
            unset($data['password1']);
            unset($data['password2']);
            $update = Db::table('cwcms_users')->insertGetId($data);
            if($update){
                $rule['group_id']   = intval(input('post.rule'));
                $rule['uid'] = intval($update);
                $roleadd = Db::name('auth_group_access')->insert($rule);
                if($roleadd){
                    $json['code']=200;
                    $json['msg']='添加成功';
                    return json($json);  
                }else{
                    $json['code']=0;
                    $json['msg']='权限分组错误';
                    return json($json); 
                }
            }else{
                $json['code']=0;
                $json['msg']='添加失败';
                return json($json);
            }
        }
        $rules = Db::name('auth_group')->select();
        $this->assign('rules',$rules);
        return $this->fetch();
    }
    	
    public function edit(){
         if(Request::instance()->isGet()){
            $data['id'] = intval(input('get.id'));
            $userinfo = Db::table('cwcms_users')->find($data['id']);
            $roles = Db::name('auth_group')->select();
            $this->assign('roles',$roles);
            $this->assign('userinfo',$userinfo);
           
        }
        if(Request::instance()->isAjax()){
            $data['password'] = trim(input('post.password'));
            $data['id'] = intval(input('post.id'));
            $data['username'] = trim(input('post.username'));
           
            $password1 = trim(input('post.password1'));
            $password2 = trim(input('post.password2'));
            $data['phone']  = trim(input('param.phone'));
            $data['email']  = trim(input('param.email'));
            $data['uid']    =   intval(input('post.rule'));
            if($data['password']){
                if(!preg_match('/^[A-Za-z0-9]{4,40}$/',$data['username'])){
                $json['code']=402;
                $json['msg']='用户名不能为汉字';
                return json($json);
                }
                $check = Db::table('cwcms_users')->where('id',$data['id'])->find();
                if(md5(md5($data['password']).md5('ChuckWe')) != $check['password'] || $data['password'] == null){
                    $json['code']=400;
                    $json['msg']='原始密码错误';
                    return json($json); 
                }
                if($password1 == $data['password'] || $password1 !== $password2 || $password1 == null || $password2 == null){
                    $json['code']=404;
                    $json['msg']='修改失败,请检查密码';
                    return json($json);
                }
                if(!preg_match('/^[a-zA-Z]\w{5,17}$/',$password1)){
                    $json['code']=401;
                    $json['msg']='密码字母开头，6-18之间';
                    return json($json);
                }
            $data['password'] = md5(md5($password1).md5('ChuckWe'));
            $update = Db::table('cwcms_users')->update($data);
            }else{
                
                array_shift($data);
                $update = Db::table('cwcms_users')->update($data);
            }
            if($update){
                $rule['group_id'] = $data['uid'];
                $rule['uid'] = $data['id'];
                $roleedit = Db::name('auth_group_access')->where('uid',$rule['uid'])->update(['group_id' => $rule['group_id']]);
               
                    $json['code']=200;
                    $json['msg']='状态修改成功';
                    return json($json);  
            }else{
                $json['code']=0;
                $json['msg']='修改失败,未更新数据';
                return json($json);
            }

        }
            return $this->fetch();

    }
    public function admin_list(){
        if (Request::instance()->isAjax()){
            $data['id'] = intval(input('post.id'));
            $data['del'] = intval(input('post.del'));
            $update = Db::table('cwcms_users')->update($data);
            if($update){
                $json['code'] = 200;
                $json['msg'] = '更改成功';
                return json($json);
            }else{
                $json['id'] = $data['id'];
                $json['del'] = $data['del'];
                $json['code'] = 0;
                $json['msg'] = '更改失败';
                return json($json);
            }
        }
        $users = Db::table('cwcms_users')->select();
        if(Request::instance()->isPost()){
            $search = trim(input('post.search'));
            Log::record("{$search}");
            $users = Db::table('cwcms_users')->where('username','like',"%{$search}%")->select();
        }
        $counts = count($users);
        foreach ($users as $key => $v) {
            $group = Db::name('auth_group')->where('id',$v['uid'])->find();
            $users[$key]['group'] = $group;
        }
        $this->assign('counts',$counts);
        $this->assign('users',$users);
    	return $this->fetch();
    }
    public function password_edit(){
        
    	return $this->fetch();
    }
    public function permission(){
        $rules = Db::name('auth_rule')->select();
        $counts = count($rules);
        $tree = new \lib\Data();
        $rules = $tree->tree($rules,'title','id','pid');
        $this->assign('rules',$rules);
        $this->assign('counts',$counts);
    	return $this->fetch();
    }
    public function permission_add(){
        if (Request::instance()->isAjax()){
            $data['title'] = trim(input('post.title'));
            $data['name']   = trim(input('post.rolename'));
            $data['pid'] = intval(input('post.pid'));
            if($data['title'] == null){
                $json['code'] = 400;
                $json['msg'] = '权限名称不能为空';
                $json['icon'] = 2;
                return json($json);
            }
            $rule = Db::name('auth_rule')->insert($data);
            if(!$rule){
                $json['code'] = 404;
                $json['msg'] = '添加错误!';
                $json['icon'] = 2;
                return json($json);
            }else{
                $json['code'] = 200;
                $json['msg'] = '添加成功!';
                $json['icon'] = 1;
                return json($json);
            }
        }
        $rules = Db::name('auth_rule')->select();
        $rules = getTree($rules);
        $this->assign('rules',$rules);
        return $this->fetch();
    }

    public function permission_edit(){
        $data['id'] = intval(input('param.id'));
        $permission_info = Db::name('auth_rule')->where('id',$data['id'])->find();
        $this->assign('pinfo',$permission_info);
        if(Request::instance()->isAjax()){
            $data['id'] = intval(input('param.id'));
            $data['title'] = trim(input('param.title'));
            $data['name'] = trim(input('param.name'));
            if($data['title'] == null || $data['name'] == null){
                $json['code'] = 400;
                $json['msg'] = '不能为空';
                $json['icon'] = 2;
                return json($json);
            }
            $permission_info = Db::name('auth_rule')->update($data);
            if($permission_info){
                $json['code'] = 200;
                $json['msg'] = '更新成功!';
                $json['icon'] = 1;
                return json($json);
            }else{
                $json['code'] = 0;
                $json['msg'] = '更新失败，请检查参数!';
                $json['icon'] = 2;
                return json($json);
            }
        }
        return $this->fetch();
    }

    public function permission_del(){
        $data['id'] = input('param.id/s');
         if($data['id'] == '0'){
            $del = input('param.del/a');
            $ids=[];

            foreach ($del as $v => $k) {
                if(!empty($k)){
                    $rules = Db::name('auth_rule')->where('pid',$k)->select(); 
                    if($rules){
                        $json['code'] = 0;
                        $json['msg'] = "删除失败,请先删除下级菜单！";
                        return json($json);
                        break;
                    }
                    $ids[$v] = $k;    
                }
            }
            foreach ($ids as $k) {
                $del = Db::name('auth_rule')->where('id',$k)->delete();
            }
            $json['code'] = 200;
            $json['msg'] = '删除成功!';
            return json($json);   
        }
        $rules = Db::name('auth_rule')->where('pid',$data['id'])->select();
        if($rules){
            $json['code'] = 0;
            $json['msg'] = '请先删除下级菜单!';
            return json($json);
        }else{
            $del = Db::name('auth_rule')->where('id',$data['id'])->delete();
            if($del){
                $json['code'] = 200;
                $json['msg'] = '删除成功!';
                return json($json);
            }else{
                $json['code'] = 0;
                $json['msg'] = '删除失败,请检查参数';
                return json($json);
            }
        }

    }

    public function role(){
        $roles = Db::name('auth_group')->select();
        $counts = count($roles);
        foreach ($roles as $key => $role) {
            $uids = Db::name('users')->where('uid',$role['id'])->select();
            $roles[$key]['uids'] = $uids;     
        }
        $this->assign('counts',$counts);
        $this->assign('roles',$roles);
    	return $this->fetch();
    }

    public function role_add(){
        $rules = Db::name('auth_rule')->select();
        

        $rules = getSon($rules,0);
        /*foreach ($rules as $key => $vol) {
            $rules[$key]['pid_rule'] = Db::name('auth_rule')->where('pid',$vol['id'])->select();
              foreach($rules[$key]['pid_rule'] as $k => $item){
                $result = Db::name('auth_rule')->where('pid',$item['id'])->select();
                        $rules[$key]['pid_rule'][$k]['tid_rule'] = $result;
                }  
        }*/
        if (Request::instance()->isAjax()){
            if(!input('post.title') || !input('post.ftitle/a')){
                $json['code'] = 404;
                $json['msg'] = '标题或权限不能为空';
                return json($json);
            }
            $data['title'] = trim(input('post.title'));
            $data['desc'] = trim(input('post.desc'));
            $data['rules'] = input('post.ftitle/a');
            $data['rules'] = implode(",", $data['rules']);
            //$data['rules'] = serialize($data['rules']);
            $data['status'] = 1;
            $add = Db::name('auth_group')->insert($data);
             if($add){
                $json['code'] = 200;
                $json['msg'] = '添加成功！';
                return json($json);
            }else{
                $json['code'] = 0;
                $json['msg'] = '添加失败,请检查参数!';
                return json($json);
            } 

        }

        $this->assign('rules',$rules);
    	return $this->fetch('role_add2');
    }

    public function role_edit(){
        
            $data['id'] = intval(input('param.id'));
            $groupinfo = Db::name('auth_group')->find($data['id']);
            $functions = explode(',',$groupinfo['rules']);
            $rules = Db::name('auth_rule')->select();
            $rules = getSon($rules,0);
            $this->assign('functions',$functions);
            $this->assign('rules',$rules);
            $this->assign('groupinfo',$groupinfo);
        if(Request::instance()->isAjax()){
            if(!input('post.title') || !input('post.ftitle/a') || !input('post.desc'))
            {
                $json['code'] = 404;
                $json['msg'] = '必填项不能为空';
                return json($json);
            }
            $data['id'] = intval(input('post.id'));
            $data['title'] = trim(input('post.title'));
            $data['desc'] = trim(input('post.desc'));
            $data['rules'] = input('post.ftitle/a');
            $data['rules'] = implode(',',$data['rules']);
            $update = Db::name('auth_group')->update($data);

            if($update){
                $json['code'] = 200;
                $json['msg'] = '修改成功';
                return json($json);
            }else{
                $json['code'] = 0;
                $json['msg'] = '修改失败,请检查参数！';
                return json($json);
            }
        }
        return $this->fetch();
    }

    public function role_del(){
        $data['id'] = input('param.id/s');
        if($data['id'] == '0'){
            $data['id'] = input('param.del/a');
            $groups = Db::name('auth_group_access')->column('group_id');
            $ids = [];
            foreach ($data['id'] as $v => $k) {
                if(in_array($k,$groups)){
                    $json['code'] = 0;
                    $json['msg'] = '请先删除组内管理人员账号!';
                    return json($json);
                    break;
                }
                $ids[$v] = $k;
            }
            foreach ($ids as $k) {
                $del = Db::name('auth_group')->where('id',$k)->delete();
            }
            $json['code'] = 200;
            $json['msg'] = '删除成功!';
            return json($json);   
        }
            $del = Db::name('auth_group')->where('id',$data['id'])->delete();
            if($del){
            $json['code'] = 200;
            $json['msg'] = '删除成功!';
            return json($json);
            }else{
            $json['code'] = 0;
            $json['msg'] = '请先删除组内管理人员账号!';
            return json($json);  
            }
            
    }


    public function del(){
            
            $data['id'] = input('param.id/s');
            if($data['id'] == '0'){
                $data['id'] = input('param.del/a');
                if(in_array('1', $data['id'])){
                    $json['code'] = 0;
                    $json['msg'] = '删除失败,原始管理员账号不能删除!';
                    $json['icon'] = 2;
                    return json($json);  
                }
                foreach ($data['id'] as $key => $v) {
                    $del = Db::name('users')->where('id',$v)->delete();
                }
                $json['code'] = 200;
                $json['msg'] = '删除成功！';
                $json['icon'] = 1;
                return json($json); 

            }
            $del = Db::name('users')->where('id',$data['id'])->delete();
            if($del){
                $json['code'] = 200;
                $json['msg'] = '删除成功！';
                $json['icon'] = 1;
                return json($json);
            }else{
                $json['code'] = 0;
                $json['msg'] = '删除失败,请检查参数!';
                $json['icon'] = 2;
                return json($json);
            }   
    }

    public function menu_list(){
        $menu = $this->menu;
        $counts = count($menu);
        $tree = new \lib\Data();
        $menu_tree = $tree->tree($menu,'menuname','id','pid');
        $this->assign('menu',$menu_tree);
        $this->assign('counts',$counts);
        return $this->fetch();
    }

    public function menu_ctrl(){
        $ctrl = trim(input('param.fun')); //get获取fun
        $menu = $this->menu;
        $menu = getTree($menu);
        $this->assign('menu',$menu);
        $this->assign('ctrl',$ctrl);
        if($ctrl == 'add'){ //进入添加模块

            if(Request::instance()->isAjax()){
                $data['menuname'] = trim(input('param.title'));
                $data['href'] = trim(input('param.menuname'));
                $data['pid'] = intval(input('param.pid'));
                $data['icon'] = input('param.icon')?input('param.icon'):'';
                if(empty($data['menuname'])){
                    return ajaxShow('','404','带星号不能为空','2');
                }
                $result = Db::name('menu')->insert($data);
                if($result){
                    return ajaxShow();
                }else{
                    return ajaxShow('','404','添加失败','2');
                }  
            }
            return $this->fetch(); 
              
        }
        if($ctrl == 'edit'){
            $id = intval(input('param.id'));
            $info = Db::name('menu')->find($id);
            $this->assign('info',$info);
            if(Request::instance()->isAjax()){
                $data['menuname'] = trim(input('param.title'));
                $data['href'] = trim(input('param.menuname'));
                $data['pid'] = intval(input('param.pid'));
                if(empty($data['menuname'])){
                    return ajaxShow('','404','带星号不能为空','2');
                }
                $result = Db::name('menu')->where('id',$id)->update($data);
                if($result){
                    return ajaxShow();
                }else{
                    return ajaxShow('','404','添加失败','2');
                }  
            }
            return $this->fetch(); 
        }
        if($ctrl == 'del'){
            $data['id'] = input('param.id/s');
            if($data['id'] == '0'){
                $del = input('param.del/a');
                $delnum = array();
                foreach ($del as $key => $val) {
                    if(!empty($val)){
                        $rules = Db::name('menu')->where('pid',$val)->select(); 
                        if($rules){
                            return ajaxShow('','400','删除失败,请先删除下级菜单！','2');
                            break;
                        }
                        $delnum[] = $val;
                    }
                }
                $sql = implode(',', $delnum);
                $delresult = Db::name('menu')->where("id in ($sql)")->delete();
                if($delresult){
                    return ajaxShow('','200',"删除{$delresult}信息成功",'1');
                }else{
                    return ajaxShow('','400','删除失败,请重试','2');
                }
            }
            $delresult = Db::name('menu')->where('id = :id',['id'=>$data['id']])->delete();
            if($delresult){
                    return ajaxShow('','200',"删除{$delresult}信息成功",'1');
                }else{
                    return ajaxShow('','400','删除失败,请重试','2');
                }
        }
        
    }
}